import axios from 'axios'
// 引入qs库解决axios post请求体的问题
import qs from 'qs';

const service = axios.create({
    baseURL: '/api',
    timeout: 5000
})

//请求拦截器 
service.interceptors.request.use(
    config => {
      // if (this.store.getters.token) {
      //   //   执行加添token操作
      //   config.headers['Authorization'] = 'bearer' + this.store.getters.token
      // }
      return config
    },
    error => {
      return Promise.reject(error)
    }
  )

//响应拦截器 
service.interceptors.response.use(
    response => {
      const res = response.data
      if (res.status !== 0) {
        return Promise.reject(new Error(res.message || 'Error'))
      } else {
        return res
      }
    },
    error => {
      return Promise.reject(error)
    }
  )
  
  export function get(url,params) {
      return new Promise((resolve,reject) => {
        service.get(url,{
              params:params
          }).then(res => {
              resolve(res)
          }).catch(err => {
              reject(err)
          })
      })
  } 
  export function post(url,params) {
      return new Promise((resolve,reject)=> {
        service.post(url,qs.stringify(params)).then(res=> {
              resolve(res)
          }).catch(err => {
              reject(err)
          } )
      })
  }